package com.henme.crm.service.admin.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.henme.crm.dao.admin.RoleMapper;
import com.henme.crm.entity.admin.Role;
import com.henme.crm.service.admin.RoleService;
import com.henme.crm.util.aop.DataSourceAnnotation;
import com.henme.crm.util.page.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {

    protected static Logger logger =  LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    RoleMapper roleMapper;

    @Override
    public List<Role> getRoleList() {
        return roleMapper.getRoleList();
    }

    @Override
    @DataSourceAnnotation("xxx")
    public void insertRole(Role role) {
        roleMapper.insertOne(role);
    }

    @Override
    public void updateRole(Role role) {
        roleMapper.updateOne(role);
    }

    @Override
    public void deleteRole(Long id) {
        roleMapper.deleteOne(id);
    }

    @Override
    public Role getRole(Long id) {
        return roleMapper.selectOne(id);
    }

    @Override
    public List<Role> getRoleListByuserid(Long id) {
        return roleMapper.getRoleListByuserid(id);
    }

    public Page<Role> getRoleList(Page<Role> page){
        List<Role> result = roleMapper.findRolePage(page);
        page.setResult(result);
        return page;
    }

    @Override
    public void savePermission(Long roleId, String[] permissionids) {
        roleMapper.deleteRolePermission(roleId);
        if (permissionids.length > 0) {
            List<Map<String, Object>> l = Lists.newArrayList();
            for (String m : permissionids) {
                Map<String, Object> param = Maps.newHashMap();
                param.put("role_id", roleId);
                param.put("authority_id",m);
                l.add(param);
            }
            roleMapper.insertRolePermissionBatch(l);
        }
    }
}
